package com.douwong.student.fragment;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.text.InputType;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.douwong.student.R;
import com.douwong.student.adapter.OnLineStudyAdapter;
import com.douwong.student.application.BaseApplication;
import com.douwong.student.base.BaseAppFragment;
import com.douwong.student.contant.Config;
import com.douwong.student.contant.NetConfig;
import com.douwong.student.model.AppInfos;
import com.douwong.student.model.StatusCode;
import com.douwong.student.utils.AppCacheManager;
import com.douwong.student.utils.CyptoUtils;
import com.douwong.student.utils.FileUtils;
import com.douwong.student.utils.LogUtils;
import com.douwong.student.utils.NetUtils;
import com.douwong.student.utils.PreferencesUtils;
import com.douwong.student.utils.ToastUtils;
import com.douwong.student.utils.UIUtils;
import com.douwong.student.view.MyCommonCallback;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * @autor yichao
 * @time 2016/11/1517:12
 * @des 在线学习
 */
@SuppressLint("ValidFragment")
public class StudyFragment extends BaseAppFragment {
    private static final String TAG = "StudyFragment";
    private ArrayList<AppInfos> onLineList = new ArrayList<AppInfos>();
    private OnLineStudyAdapter mOnLineStudyAdapter;

    /**
     * 打开网页
     *
     * @param position
     */

    protected void openStudyResource(int position) {
        if (!NetUtils.NetwrokIsUseful(getActivity())){
            ToastUtils.makeText(getActivity(),UIUtils.getString(R.string.please_connection_network));
            return;
        }
        AppInfos appInfos = onLineList.get(position);
        String url = appInfos.appDownloadUrl;
        if (appInfos.appPageCode > 0) {
            if (BaseApplication.sUserBean != null) {
                String key = BaseApplication.sUserBean .getUserbean().getEuNumber() + "|" + CyptoUtils.MD5("123456");
                String trunKey;
                try {
                    trunKey = encodeBase64(key.getBytes("utf-8"));
                   // url=url.replace("www","xiaodou");
                    if (appInfos.appName.equals("我的班级")){
                        url = url +"?pageCode="+appInfos.appPageCode+"&classid="+BaseApplication.sUserBean.getClassId()
                                +"&key="+ trunKey;
                    }else {
                        url = url +"?pageCode="+appInfos.appPageCode+"&key="+ trunKey;
                    }

                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(getActivity(), "请先登录！", Toast.LENGTH_LONG).show();
                return;
            }
        }


        Log.d(TAG, "requet url : " + url);
        Intent it = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        it.setClassName("com.android.browser", "com.android.browser.BrowserActivity");
        try {
            getActivity().startActivity(it);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }
    }

    @Override
    protected void initData() {
        super.initData();
        ArrayList<AppInfos>  mLocalList = (ArrayList<AppInfos>) AppCacheManager.readObject(getActivity(), Config.ONLINE_STUDY_RESOURE);
        if (mLocalList!=null&&!mLocalList.equals("")){
            onLineList=mLocalList;
            mAppGv.setVisibility(View.VISIBLE);
            mRlFreshContainer.setVisibility(View.INVISIBLE);
            mLlLoading.setVisibility(View.INVISIBLE);
        }
        mOnLineStudyAdapter = new OnLineStudyAdapter(onLineList, getActivity());
        mAppGv.setAdapter(mOnLineStudyAdapter);
    }
    public static String encodeBase64(byte[] b) {
        return Base64.encodeToString(b, Base64.DEFAULT);
    }

    /**
     * 加载数据
     */
    @Override
    protected void loadData() {
        if (!NetUtils.NetwrokIsUseful(getActivity())){
            ToastUtils.makeText(getActivity(),UIUtils.getString(R.string.please_connection_network));
            return;
        }
        mAppGv.setVisibility(View.INVISIBLE);
        mRlFreshContainer.setVisibility(View.INVISIBLE);
        mLlLoading.setVisibility(View.VISIBLE);
        Map<String, String> map = new HashMap<>();
        map.put(Config.APPTYPE, "748");
        NetUtils.Get(NetConfig.APP_LIST_URL, map, new MyCommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                super.onSuccess(result);
                mRlFreshContainer.setVisibility(View.INVISIBLE);
                mLlLoading.setVisibility(View.INVISIBLE);
                mAppGv.setVisibility(View.VISIBLE);
                FileUtils.writeFile(result.getBytes(), Environment.getExternalStorageDirectory().getAbsolutePath(), "onlineStudy.txt");
                onLineList.clear();
                StatusCode<String> sc = (StatusCode<String>) JSON
                        .parseObject(result,
                                new TypeReference<StatusCode<String>>() {
                                });
                if (sc != null && sc.isFlag()) {
                    ArrayList<AppInfos> list = (ArrayList<AppInfos>) JSON.parseArray(sc.getData(), AppInfos.class);//线上的数据
                    if (list != null) {
                        for (AppInfos appinfo : list) {
                            if (appinfo.ynShow == 1) {

                                onLineList.add(appinfo);
                            }
                        }
                        boolean b = AppCacheManager.saveObject(getActivity(), onLineList, Config.ONLINE_STUDY_RESOURE);
                        LogUtils.i(TAG,b+"");
                        mOnLineStudyAdapter.setOnLineList(onLineList);
                        mOnLineStudyAdapter.notifyDataSetChanged();

                    }

                }

            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                if (onLineList!=null&&!onLineList.equals("")){
                    mAppGv.setVisibility(View.VISIBLE);
                    mRlFreshContainer.setVisibility(View.INVISIBLE);
                    mLlLoading.setVisibility(View.INVISIBLE);
                }

            }
        });
    }

    @Override
    protected void onItemClick(final int position) {
      //  LogUtils.i(TAG, "AdapterView" + parent.getClass() + "___view:" + view.getClass() + "___position:" + position + "____id:" + id);
        boolean isPatriarch = PreferencesUtils.getInstance().getBoolean(Config.IS_PATRIARCH, false);
        if (isPatriarch) {
            //开启家长模式
            //判断是否上锁
            if (onLineList.get(position).ynControl == 1) {
                //上锁
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                String[] str3 = new String[]{"打开", "关闭密码"};
                builder.setItems(str3, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            //打开网页
                            openStudyResource(position);

                        } else {
                            //关闭密码
                            onLineList.get(position).ynControl = 0;
                            mOnLineStudyAdapter.setOnLineList(onLineList);
                            mOnLineStudyAdapter.notifyDataSetChanged();
                        }

                    }
                });
                builder.show();

            } else {
                //没锁
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
                String[] str4 = new String[]{"打开", "开启密码"};
                builder.setItems(str4, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        if (which == 0) {
                            //打开网页
                            openStudyResource(position);

                        } else {
                            //开启密码
                            onLineList.get(position).ynControl = 1;
                            mOnLineStudyAdapter.setOnLineList(onLineList);
                            mOnLineStudyAdapter.notifyDataSetChanged();
                        }

                    }
                });
                builder.show();


            }
        } else {
            //家长模式关闭
            if (BaseApplication.isTimeControl){
                openStudyResource(position);
            }else {
                //判断加锁
                if (onLineList.get(position).ynControl == 1) {
                    //加锁
                    final EditText input = new EditText(getActivity());
                    input.setHeight(100);
                    input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    final AlertDialog.Builder builde = new AlertDialog.Builder(getActivity());
                    builde.setTitle("输入密码").setIcon(android.R.drawable.ic_dialog_info).setView(input)
                            .setNegativeButton("取消", null);
                    builde.setPositiveButton("确定", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int which) {
                            String sec = input.getText().toString();

                            String password = PreferencesUtils.getInstance().getString(Config.FAMILY_KEY_PWD, "");
                            if (!password.equals("")){
                                BaseApplication.AppKeyPWD=password;
                            }
                            if (BaseApplication.AppKeyPWD.equals(sec.trim())) {
                                openStudyResource(position);
                            } else {
                                ToastUtils.makeText(getActivity(),"密码错误！");
                            }
                        }
                    });

                    builde.show();
                } else {
                    //没锁
                    openStudyResource(position);

                }
            }

        }
    }



}
